# -*- coding: utf-8 -*-

"""
@author: bw
@contact: bw@handsdriver.net
"""

import functools

import plumbum.machines.env as _plmenv

from . import path as _vgpath


class VagrantEnviron(_plmenv.BaseEnv):
	def __init__(self, machine):
		"""
		session = remote._session

		# GNU env has a -0 argument; use it if present. Otherwise,
		# fall back to calling printenv on each (possible) variable
		# from plain env.

		env0 = session.run("env -0; echo")

		if env0[0] == 0 and not env0[2].rstrip():
			self._curr = dict(
				line.split('=', 1) for line in env0[1].split('\x00')
				if '=' in line)
		else:
			lines = session.run("env; echo")[1].splitlines()
			split = (line.split('=', 1) for line in lines)
			keys = (line[0] for line in split if len(line) > 1)
			runs = ((key, session.run('printenv "%s"; echo' % key))
					for key in keys)
			self._curr = dict(
				(key, run[1].rstrip('\n')) for (key, run) in runs
				if run[0] == 0 and run[1].rstrip('\n') and not run[2])

		self._orig = self._curr.copy()
		"""

		self.machine = machine
		self._curr = {}
		super().__init__(functools.partial(_vgpath.VagrantPath, machine), machine.pathsep)

#	@_setdoc(BaseEnv)
#	def __delitem__(self, name):
#	@_setdoc(BaseEnv)
#	def __setitem__(self, name, value):
#	@_setdoc(BaseEnv)
#	def pop(self, name, *default):
#	@_setdoc(BaseEnv)
#	def update(self, *args, **kwargs):
#	def getdelta(self):

	def expand(self, expr):
		return self.machine.getSession().run('echo ' + expr)[1].strip()

	def expanduser(self, expr):
		if not any(part.startswith('~') for part in expr.split(self.machine.sep)):  # @xxx: escape & quote
			return expr
		# we escape all $ signs to avoid expanding env-vars
		return self.machine.getSession().run('echo ' + expr.replace('$', '\\$'))[1].strip()
